<?php
namespace Controller;

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Container;


class MsgApi extends Base
{

    public function __construct(Container $container)
    {
        parent::__construct($container);

    }

    public function sendmsg(Request $req, Response $res)
    {
        $host = "http://dingxin.market.alicloudapi.com/dx/sendSms";
        $msg = $this->msg;
        $appcode = $msg['code'];
        $param = "";
        for ($i = 0; $i < 4; $i++) {
            $param .= rand(0, 9);
        }

        $curl = $this->curl;

        $curl->setHeader("Authorization", "APPCODE " . $appcode);
        $curl->post($host, [
                'mobile' => trim($req->getParam('mobile')),
                'param' => "code:$param",
                'tpl_id' => (string)trim($msg['tpl_id'])
            ]
        );
        $response = json_decode($curl->response, true);
        if ($response['return_code'] === "00000") {
            $_SESSION['param'] = trim($param);
            return $res->withStatus(200)->write('短信发送成功');
            exit;
        } else {
            return $res->withStatus(400)->write('短信发送失败,errorcode:' . $response['return_code']);
            exit;
        }


    }

    public function register(Request $req, Response $res)
    {
        $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
        if ($validate) {
            if ($req->getParam('u_code') === $_SESSION['param']) {
                $openid = $_SESSION['openid'];
                $where['openid'] = array("'$openid'");

                if (!empty($this->db->where($where)->count('tcp_user'))) {
                    return $res->withStatus(400)->write('该微信号已经注册');
                    exit;
                }

                if ($this->checkfrom->regex('require', $req->getParam('username')) === false) {
                    return $res->withStatus(400)->write('姓名为空');
                    exit;
                }
                if ($this->checkfrom->Mobile_check($req->getParam('mobile'), array(1, 2, 3)) === false) {
                    return $res->withStatus(400)->write('手机号格式错误');
                    exit;
                }

                if ($this->checkfrom->regex('require', $req->getParam('birthday')) === false) {
                    return $res->withStatus(400)->write('生日为空');
                    exit;
                }
                if ($this->checkfrom->regex('require', $req->getParam('region')) === false) {
                    return $res->withStatus(400)->write('地区为空');
                    exit;
                }
                if ($this->checkfrom->regex('require', $req->getParam('city')) === false) {
                    return $res->withStatus(400)->write('城市为空');
                    exit;
                }
                $mobile = $req->getParam('mobile');
                $wheremobile['mobile'] = array("'$mobile'");
                if (!empty($this->db->where($wheremobile)->count('tcp_user'))) {
                    return $res->withStatus(400)->write('该手机号已经注册');
                    exit;
                }
                $_userdata = [
                    'openid' => $_SESSION['openid'],
                    'username' => $req->getParam('username'),
                    'mobile' => $req->getParam('mobile'),
                    'birthday' => strtotime($req->getParam('birthday')),
                    'sex' => $req->getParam('sex'),
                    'region' => $req->getParam('region'),
                    'city' => $req->getParam('city'),
                    'area' => $req->getParam('area'),
                    'updatetime' => time(),
                    'regtime' => time(),

                ];
             //注册 用户ID
                $invitation_uid= $this->db->insertid('tcp_user', $_userdata);

                if (empty($invitation_uid)) {
                    return $res->withStatus(400)->write('注册失败');
                    exit;
                } else {
                    $_SESSION['uid'] = $invitation_uid;
                    $success = 0;
                    $badydata = $req->getParam('babydata');
                    if ($badydata) {
                        foreach ($badydata as $value) {
                            if(!empty($value['childrenname'])&&!empty($value['sex'])&&!empty($value['birthday'])){
                                $children = $this->db->insert('tcp_user_children', [
                                    'uid' => $invitation_uid,
                                    'childrenname' => $value['childrenname'],
                                    'sex' => $value['sex'],
                                    'birthday' => strtotime($value['birthday'])

                                ]);
                                if ($children) {
                                    $success++;
                                    continue;
                                } else {
                                    $success = 0;
                                    break;
                                }
                            }else{
                                continue;
                            }

                        }
                        if(!empty($req->getParam('uid'))){
                            $uid=$req->getParam('uid');
                            $invitationdata=[
                                'uid'=>$uid,
                                'invitation_uid'=>$invitation_uid,
                                'createtime'=>time()
                            ];
                            $_invitationwhere['uid']=array($uid);
                            $_invitationwhere['invitation_uid']=array($invitation_uid);

                            if(empty($this->db->where($_invitationwhere)->count('tcp_user_invitation'))){
                                $this->db->insert('tcp_user_invitation', $invitationdata);
                            }
                            if (!empty($success)) {
                                return $res->withStatus(200)->write('注册成功');
                                exit;
                            } else {
                                return $res->withStatus(400)->write('注册失败');
                                exit;
                            }

                        }else{
                            if (!empty($success)) {
                                return $res->withStatus(200)->write('注册成功');
                                exit;
                            } else {
                                return $res->withStatus(400)->write('注册失败');
                                exit;
                            }
                        }

                    }
                }
            } else {
                return $res->withStatus(400)->write('验证码错误');
                exit;
            }


        } else {
            return $res->withStatus(400)->write('guard error');
            exit;
        }
    }

    public function saveuserinfo(Request $req, Response $res)
    {
        $user = $this->getUser();
        if (empty($user)) {
            return $res->withStatus(400)->write('no user');
            exit;
        } else {
            $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
            if ($validate) {

                if ($this->checkfrom->regex('require', $req->getParam('username')) === false) {
                    return $res->withStatus(400)->write('姓名为空');
                    exit;
                }
                if ($this->checkfrom->Mobile_check($req->getParam('mobile'), array(1, 2, 3)) === false) {
                    return $res->withStatus(400)->write('手机号格式错误');
                    exit;
                }


                if ($this->checkfrom->regex('require', $req->getParam('region')) === false) {
                    return $res->withStatus(400)->write('地区为空');
                    exit;
                }
                if ($this->checkfrom->regex('require', $req->getParam('city')) === false) {
                    return $res->withStatus(400)->write('城市为空');
                    exit;
                }
                $mobile = $req->getParam('mobile');
                $wheremobile['mobile'] = array("'$mobile'");
                $wheremobile['uid'] = array($user['uid'],'<>');
                if (!empty($this->db->where($wheremobile)->count('tcp_user'))) {
                    return $res->withStatus(400)->write('该手机号已经注册');
                    exit;
                }
                $_userdata = [
                    'username' => $req->getParam('username'),
                    'mobile' => $req->getParam('mobile'),
                    'sex' => $req->getParam('sex'),
                    'region' => $req->getParam('region'),
                    'city' => $req->getParam('city'),
                    'area' => $req->getParam('area'),
                    'updatetime' => time(),
                    'regtime' => time(),

                ];

                if (empty($this->db->where(['uid'=>$user['uid']])->update('tcp_user', $_userdata))) {
                    return $res->withStatus(400)->write('保存失败');
                    exit;
                } else {
                    $badydata =$req->getParam('babydata');
                    if ($badydata) {
                        foreach ($badydata as $value) {
                            if(!empty($value['childrenname'])&&!empty($value['sex'])&&!empty($value['birthday'])){
                                if(empty($value['cid'])){
                                    $this->db->insert('tcp_user_children', [
                                        'uid' => $user['uid'],
                                        'childrenname' => $value['childrenname'],
                                        'sex' => $value['sex'],
                                        'birthday' => strtotime($value['birthday'])

                                    ]);
                                }else{
                                    $this->db->where(['cid'=>$value['cid']])->update('tcp_user_children', [
                                        'uid' => $user['uid'],
                                        'childrenname' => $value['childrenname'],
                                        'sex' => $value['sex'],
                                        'birthday' => strtotime($value['birthday'])

                                    ]);

                                }

                            }else{
                                continue;
                            }
                        }
                        return $res->withStatus(200)->write('保存成功');
                        exit;
                    }else{
                        return $res->withStatus(200)->write('保存成功');
                        exit;
                    }
                }
            } else {
                return $res->withStatus(400)->write('guard error');
                exit;
            }
        }
    }

}